define('views/search', ['jquery', 'utils/debounce', 'views/datalist'], function ($, debounce, DataList) {

    var searchInput = $('input.search-input')
    Init()

    function Init() {
        // 点击展开检索
        $('.search-content-min-content').on('click', function () {
            $(this).parent().removeClass('search-content-min')
            searchInput.focus()
        })
        // 点击收起检索面包
        $('.search-content-min-btn').on('click', function () {
            $(this).closest('div.search-content').addClass('search-content-min')
        })

        // 输入检索内容
        searchInput.on('input', debounce(SearchArea, 200))
        searchInput.on('focus', function(){
            $('.search-result').addClass('search-result-show')
        })
        searchInput.on('blur', function(){
            setTimeout(function(){
                $('.search-result').removeClass('search-result-show')
            }, 300)
        })

        $('ul.search-result-list').on('click', 'li', function () {
            var target = $(this)
            $('.search-result').removeClass('search-result-show')

            var district = this.getAttribute('district')
            var name = target.children('.poi-name').text()
            var location = this.getAttribute('location').split(',')
            var lng = location[0]
            var lat = location[1]
            var latlng = L.latLng(Number(lat), Number(lng))
        //    先判断当前点击的结果属于那个市，然后自动选择该市
            var areas = district.split(/自治区|省|区|市/)
            // areas = areas.filter( function(item) {!!item})

            for(var i=areas.length-1;i>=0;i--){
                if(!areas[i]){
                    areas.splice(i,1)
                }
            }

            if(areas.length>=2){
                if(window.citys[areas[0]]){
                    $('#provice').selectpicker('val',areas[0])
                    $('#provice').change()
                }
                if(window.citys[areas[0]] && window.citys[areas[0]][areas[1]]){
                    $('#city').selectpicker('val',areas[1])
                    $('#city').change()
                }
            }else if(areas.length==1){
                if(window.citys[areas[0]]){
                    $('#provice').selectpicker('val',areas[0])
                    $('#provice').change()
                }
            }

             // 展示小区点信息，以及当前小区及其周边的数据
             ShowSelectPosition(latlng, { name: name })
             window.map.setView(latlng, 13)
            // $('.search-content-min-btn').click()

            return false
        })

    }

    // 执行检索操作
    function SearchArea() {
        var keywords = searchInput.val()
        if (keywords.length === 0) {
            //  清理检索结果和图面数据
            var target = $('.search-result-list')
            target.empty()
            $('.search-result').removeClass('search-result-show')
            return
        }
        $('.search-result').addClass('search-result-show')
        // 使用高德地图检索poi
        GaoDePOISearch(keywords).done(function (response) {
            console.log(response)
            if (response.status === "1") {
                ShowSearchResult(response.tips)
            } else {
                console.log('poi检索失败')
            }
        }).fail( function(error){
            console.log(error)
        })
    }


    /**
     * 高德地图检索poi功能
     * @param {*} keywords 
     * @param {*} city 
     */
    function GaoDePOISearch(keywords, city) {
        var key =  window.randomKey() 
        var types = '190400|991000'
        var city = $('#city').val()
        // poi 检索
        // const url = `https://restapi.amap.com/v3/place/text?key=${key}&keywords=${keywords}&types=${types}`
        // const url = `https://restapi.amap.com/v3/place/text?key=${key}&keywords=${keywords}&types=${types}&city=${city}`
        // 输入提示
        var url = "https://restapi.amap.com/v3/assistant/inputtips?key="+key+"&keywords="+keywords
        url += '&city='+city

        return $.ajax({
            url: url,
            type: 'get',
            dataType: 'json',
        })
    }

    /**
     * 根据poi的id检索poi详情
     * @param {*} id 
     */
    function GaoDePOIDetail(id){
        var key =  window.randomKey() 
        var url = 'https://restapi.amap.com/v3/place/detail?key='+key+'&id='+id
        return $.ajax({
            url :url,
            type:'get',
        })
    }

    /**
     * 展示检索结果
     * @param {*} results 
     */
    function ShowSearchResult(results) {
        var content = $('.search-result')
        var target = $('.search-result-list')
        target.empty()
        if (results.length > 0) {
            var html = ''
            results.forEach(function(element) { 

                if(element.district.length==0 && element.location.length==0){
                    // 如果搜索结果中有空的就跳过
                }else{
                    html += '<li class="search-result-list-item" '
                    +'location="'+element.location+'" '
                    +'poi-id="'+element.id+'" '
                    +'district="'+element.district+'" '
                    +'adcode="'+element.adcode+'">'
                    +'<span class="glyphicon glyphicon-map-marker poi-icon"></span>'
                    +'<span class="poi-name">'+element.name+'</span>'
                    +'<span class="poi-address">'+element.district +'</span>'
                    +'</li>'
                }
            });
            target.html(html)
        } else {
            target.html('<li style="text-align:center;margin-top:100px"><span>没有检索结果！</span></li>')
        }
    }

    /**
     * 在地图上先当前点击对的检索结果位置
     * @param {L.latLng} latlng 
     * @param {Object} attribute 
     */
    function ShowSelectPosition(latlng, attribute) {

        GetRoundInfo(latlng).done(function(data) {
            // 距离您15公里内共多少个小区存在确诊病例，共xx个确认病例，
            // 距离您最近的小区是：xx小区，距离10米/1公里

            var zoneCount = data.length
            var peopleCount = 0
            var latestZone = data.length > 0 ? data[0] : { showAddress: '', cntSumCertain: -1, fullAddress: '', distance: -1 }
            data.forEach(function(zone) {
                if (zone.cntSumCertain > 0) {
                    peopleCount += Number(zone.cntSumCertain)
                }
            })

            var popupContent = '<span style="font-size:1.4rem;display:inline-block;margin-bottom:5px">名称：'+attribute.name+'</span><br/>'
            +'15公里内曾确诊病例：<span style="color:red">'+peopleCount+'&nbsp;人</span><br/>'
            +'确认病例分布小区：<span style="color:red">'+zoneCount+'</span><br/>'
            +'距离您最近的小区：<span>'+latestZone.showAddress+'</span><br/>'
            +' 该小区距离您：'+(latestZone.distance >= 0 ? latestZone.distance.toFixed(0) : '-')+'米&nbsp;&nbsp;'
            +'曾确诊：'+(latestZone.cntSumCertain >= 0 ? latestZone.cntSumCertain : '-')+'人'


            if (window.selectedTarget) {
                window.selectedTarget.setLatLng(latlng).setPopupContent(popupContent).openPopup()
            } else {
                var popup = L.popup().setContent(popupContent)
                window.selectedTarget = L.marker(latlng).addTo(window.map).bindPopup(popup).openPopup()
            }

        }).fail(function(error){ console.error(error)})

    }

    function GetRoundInfo(latlng) {
        // 根据当前城市和选择地点的经纬度查询周边小区信息
        var url = 'http://39.99.193.71:8090/emergency/getDistanceByCity?'
        var province = $('#provice').val()
        var city = $('#city').val()
        url += 'province='+province+'&city='+city+'&lon='+latlng.lng+'&lat='+latlng.lat
        return $.ajax({
            url: url,
            type: 'get'
        })
    }

});